package day14.demo1;

/**
 * @Auther:小陈的Java
 */
public class ProductorDemo {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Thread shenchan = new Productor(clerk);
        Thread xiaofei = new Customer(clerk);
        shenchan.start();
        xiaofei.start();
    }
}
class Clerk{
    private  int productCount =0;
    public synchronized void shengChan(){
        try {
            if(productCount<20){
                notify();
                productCount++;
                System.out.println(Thread.currentThread().getName()+"生产：第"+productCount+"个产品完成");
            }else {
                wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    public synchronized void xiaoFei(){
        try {
            if (productCount>0){
                notify();
                System.out.println(Thread.currentThread().getName()+"消费：第"+productCount+"个产品完成");
                productCount--;

            }else {
                wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
class Productor extends Thread{
    private Clerk clerk;
    public Productor(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while(true){
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.shengChan();
        }
    }
}
class Customer extends Thread{
    private Clerk clerk;
    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while(true){
            try {
                sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.xiaoFei();
        }
    }
}